<template>
  <div class="pad-20 bgc-default" v-loading="fullLoading" element-loading-text="加载中">
    <div class="pad-20 bg-color-white">
      <!-- 顶部按钮 -->
      <div>
        <el-button type="primary" @click="doAuditOrder" v-if="purchaseOrderObj.purchaseOrderStatus == 1">审核</el-button>
        <el-button type="primary" @click="doStopOrder" v-if="purchaseOrderObj.purchaseOrderStatus == 2 || purchaseOrderObj.purchaseOrderStatus == 3">终止</el-button>
        <el-button @click="doRestSupplierPrice('')" v-if="purchaseOrderObj.purchaseOrderStatus == 1">重算价格</el-button>
        <el-button @click="doBack">返回上一级</el-button>
      </div>
      <!-- 顶部信息 -->
      <div class="info-top-col">
        <el-row :gutter="20" class="mar-t-20">
          <el-col :span="12">
            <ul>
              <li class="flex">
                <label class="text-align-r">采购申请单号：</label>
                <span>{{ purchaseOrderObj.purchaseOrderNo }}</span>
                <span class="font-green">（{{ dict.purchaseOrderStatus[purchaseOrderObj.purchaseOrderStatus] }}）</span>
                <span class="font-blue cursor-p font-14" @click="doClipboard(purchaseOrderObj.purchaseOrderNo, $event)">复制</span>
              </li>
              <li class="flex">
                <label class="text-align-r">供应商：</label>
                <span>{{ purchaseOrderObj.supplierName ? purchaseOrderObj.supplierName : '不限' }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">备注：</label>
                <span>{{ purchaseOrderObj.remark }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">审核意见：</label>
                <span>{{ purchaseOrderObj.auditRemark }}</span>
              </li>
            </ul>
          </el-col>
          <el-col :span="12">
            <ul>
              <li class="flex">
                <label class="text-align-r">仓库：</label>
                <span>{{ purchaseOrderObj.warehouseName }}</span>
              </li>
              <li class="flex">
                <label class="text-align-r">收货人：</label>
                <span>{{ purchaseOrderObj.consignee }}（ {{ purchaseOrderObj.consigneePhone }} ）</span>
              </li>
              <li class="flex">
                <label class="text-align-r">收货地址：</label>
                <span>{{ purchaseOrderObj.consigneeDetailAddress }}</span>
              </li>
            </ul>
          </el-col>
        </el-row>
      </div>
      <!--搜索区 -->
      <div class="top-operate-default mar-t-20">
        <div class="search-item">
          <el-select v-model="textCol">
            <el-option label="商品货号" value="goodsCode"></el-option>
            <el-option label="商品条码" value="goodsBarCode"></el-option>
            <el-option label="商品名称" value="title"></el-option>
          </el-select>
          <el-input @keyup.enter.native="doSearch" v-model.trim="textValue" placeholder="请输入内容" class="text-input"></el-input>
          <el-cascader v-model="categoryIds" 
            :props="{ checkStrictly: true }" 
            :options="categoryData" 
            filterable 
            clearable
            class="pad-l-10"
            placeholder="零售商品分类">
          </el-cascader>
          <el-select v-if="!purchaseOrderObj.supplierId" v-model="defaultQuery.supplierId" placeholder="供应商" clearable class="pad-l-10 supplier-select">
            <el-option label="无" value="0"></el-option>
            <el-option v-for="(item, index) in supplierList" :key="index" :label="item.supplierName" :value="item.supplierId"></el-option>
          </el-select>
          <el-button-group class="mar-l-20">
            <el-button type="primary" @click="doSearch">查询</el-button>
            <el-button plain @click="doResetSearch">重置</el-button>
          </el-button-group>
        </div>
      </div>
      <!-- 内容列表 -->
      <div class="table-container mar-t-20">
        <el-table :data="dataList" v-loading="listLoading" element-loading-text="加载中">
          <el-table-column min-width="360px" label="商品" fixed="left">
            <template slot-scope="scope">
              <div class="v-align-c cursor-p">
                <label><img :src="scope.row.mainImage" class="t-goods-pic"></label>
                <div class="pad-l-10">
                  <div class="line-2 width-200">
                    <span class="font-blue" :title="scope.row.title">{{ scope.row.title }}</span>
                  </div>
                  <div class="font-color-6 font-13">
                    <span>条码：{{ scope.row.goodsBarCode }}</span>
                    <br>
                    <span v-if="scope.row.categoryName">[{{ scope.row.categoryName }}]</span>
                  </div>
                </div>
              </div>
            </template>
          </el-table-column>
          <el-table-column width="180px" label="规格描述" prop="skuDetail">
          </el-table-column>
          <el-table-column width="120px" label="数量" align="center">
            <template slot-scope="scope">
              <div>申请：{{ scope.row.purchaseNum }}</div>
              <div>核定：{{ scope.row.finalNum }}</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="单价" align="center">
            <template slot-scope="scope">
              <div>￥{{ scope.row.warehouseGoodsPrice }}</div>
              <div class="font-blue">{{ scope.row.taxFlag === 1 ? '（已含税）' : '（未含税）' }}</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="金额" align="center">
            <template slot-scope="scope">
              <div>￥{{ scope.row.warehouseGoodsAmount }}</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="税额" align="center">
            <template slot-scope="scope">
              <div>￥{{ scope.row.taxPrice }}</div>
              <div class="font-blue">（{{ scope.row.taxRate }}%）</div>
            </template>
          </el-table-column>
          <el-table-column width="120px" label="价税合计" align="center">
            <template slot-scope="scope">
              <div>￥{{ scope.row.warehouseGoodsAmountWithTax }}</div>
            </template>
          </el-table-column>
          <el-table-column width="180px" label="供应商" align="center">
            <template slot-scope="scope">
              {{ scope.row.supplierName ? scope.row.supplierName : '（无）' }}
            </template>
          </el-table-column>
          <el-table-column width="120px" label="已入库数量" prop="stockInNum" align="center">
          </el-table-column>
          <el-table-column width="120px" label="已退货数量" prop="stockOutNum" align="center">
          </el-table-column>
          <el-table-column min-width="240px" label="操作" fixed="right" align="right" v-if="purchaseOrderObj.purchaseOrderStatus == 1">
            <template slot-scope="scope">
              <el-button type="text" size="medium" @click="doEdit(scope.row)">编辑</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <!-- 列表分页 -->
      <div class="pagination">
        <el-pagination background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="searchListQuery.currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="searchListQuery.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>


    <!-- 编辑商品 -->
    <el-dialog title="编辑商品" v-el-drag-dialog :visible.sync="orderGoodsVisible" width="500px" top=17vh>
      <el-form ref="orderGoodsForm" :model="orderGoodsForm" :rules="rules" label-width="120px" style="width: 460px">
        <el-form-item label="申请数量：" prop="purchaseNum">
          <span>{{ orderGoodsForm.purchaseNum }}</span>
        </el-form-item>
        <el-form-item label="核定数量：" prop="finalNum">
          <el-input v-model="orderGoodsForm.finalNum"></el-input>
        </el-form-item>
        <el-form-item label="单价：" prop="warehouseGoodsPrice">
          <div class="inline-flex">
            <el-select v-model="orderGoodsForm.taxFlag" class="width-110">
              <el-option label="含税价" value='1'></el-option>
              <el-option label="不含税价" value='0'></el-option>
            </el-select>
            <el-input v-model="orderGoodsForm.warehouseGoodsPrice" class="width-130" 
              @keyup.native="orderGoodsForm.warehouseGoodsPrice = checkInputNum(orderGoodsForm.warehouseGoodsPrice)">
            </el-input>
            <el-button type="text" size="medium" @click="doRestSupplierPrice(orderGoodsForm.purchaseOrderGoodsId)">&nbsp;&nbsp;点击重取供应价</el-button>
          </div>
        </el-form-item>
      </el-form>
      <div class="dialog-footer mar-b-10">
        <el-button type="primary" @click="doSaveOrderGoods">保存</el-button>
        <el-button @click="orderGoodsVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <!-- 采购单审核dialog -->
    <el-dialog width="500px" v-el-drag-dialog title="采购单审核" :visible.sync="auditVisible">
      <el-form ref="auditForm" :model="auditForm" :rules="rules" label-width="120px" style="width: 460px">
        <el-form-item label="审核结果：" prop="purchaseOrderStatus">
          <el-radio-group v-model="auditForm.purchaseOrderStatus">
            <el-radio :label="2">审核通过</el-radio>
            <el-radio :label="-1">审核不通过</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="审核意见：">
          <el-input type="textarea" :rows="3" v-model="auditForm.auditRemark"></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog-footer mar-b-10">
        <el-button type="primary" @click="doSaveAudit">确定</el-button>
        <el-button @click="auditVisible = false">取消</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
  import elDragDialog from '@/directive/el-dragDialog'
  import clipboard from '@/utils/clipboard'
  import { getDictByGroupName } from '@/api/common/common'
  import { listGoodsCategory } from '@/api/goods/goods'
  import { listSupplier } from '@/api/user/supplier'
  import { getPurchaseOrder, doAudit, updateBatchPurchaseOrderStatusByIds } from '@/api/warehouse/purchaseOrder'
  import { pagingPurchaseOrderGoods, doRestPrice, savePurchaseOrderGoods } from '@/api/warehouse/purchaseOrderGoods'

  export default {
    directives: {
      elDragDialog
    },
    data() {
      const validateNum = (rule, value, callback) => {
        const flag = this.validatePositiveNum(value)
        if (!flag || value <= 0) {
          callback(new Error('请输入大于0整数'))
          return
        }
        callback()
      }
      const validatePirce = (rule, value, callback) => {
        const price = parseFloat(value)
        if (Number.isNaN(price) || price < 0) {
          callback(new Error('请输入大等于0单价'))
          return
        }
        callback()
      }
      return {
        // 分类model
        categoryIds: [],
        // 文本model
        textCol: 'goodsCode',
        textValue: '',
        // 默认条件
        defaultQuery: {
          currentPage: 1,
          size: 10,
          supplierId: ''
        },
        // 查询条件
        searchListQuery: {},
        // 数据字典
        dict: {
          purchaseOrderStatus: {}
        },
        rules: {
          finalNum: [
            { required: true, message: '请输入核定数量', trigger: 'blur' },
            { validator: validateNum, trigger: 'blur' }
          ],
          warehouseGoodsPrice: [
            { required: true, message: '请输入单价', trigger: 'blur' },
            { validator: validatePirce, trigger: 'blur' }
          ]
        },
        // 采购订单对象
        purchaseOrderObj: {},
        // 采购单商品表单
        orderGoodsForm: {
          purchaseOrderGoodsId: '',
          warehouseGoodsId: '',
          purchaseNum: 0,
          finalNum: 0,
          warehouseGoodsPrice: 0,
          taxFlag: '0'
        },
        // 采购单审核表单
        auditForm: {
          purchaseOrderId: '',
          purchaseOrderStatus: 2,
          auditRemark: ''
        },
        // 页面loading
        fullLoading: false,
        // 列表loading
        listLoading: false,
        // 采购单审核visible
        auditVisible: false,
        // 商品数量编辑visible
        orderGoodsVisible: false,
        // 供应商集合
        supplierList: [],
        // 零售商品分类集合
        categoryData: [],
        total: 0,
        dataList: []
      }
    },
    // 初始化页面
    created() {
      Object.assign(this.searchListQuery, this.defaultQuery)
      const queryParams = this.getCurrentPage().query
      if (queryParams && queryParams.purchaseOrderId) {
        this.purchaseOrderObj.purchaseOrderId = queryParams.purchaseOrderId
        this.init()
        this.initList()
      }
      // 获取数据字典
      getDictByGroupName('PurchaseOrderDTO').then((response) => {
        this.dict = response.data
        for (var key in this.dict.purchaseOrderStatus) {
          if (this.dict.purchaseOrderStatus[key] === '待入库') {
            this.dict.purchaseOrderStatus[key] = '待出库'
          }
          if (this.dict.purchaseOrderStatus[key] === '部分入库') {
            this.dict.purchaseOrderStatus[key] = '部分出库'
          }
        }
      })
      const supplierForm = {
        enterpriseId: this.getEnterpriseId(),
        settlementType: 30
      }
      // 获取供应商列表
      listSupplier(supplierForm).then(response => {
        if (response.isError) return
        this.supplierList = response.data
      })
      // 获取零售商品分类
      listGoodsCategory(this.getEnterpriseId()).then(response => {
        this.categoryData = response.data
      })
    },
    methods: {
      // 初始化
      init() {
        // 获取采购订单
        this.fullLoading = true
        getPurchaseOrder(this.purchaseOrderObj.purchaseOrderId).then(response => {
          this.fullLoading = false
          this.purchaseOrderObj = response.data
        })
      },
      // 初始化列表
      initList() {
        this.listLoading = !this.fullLoading
        const size = this.searchListQuery.size
        const currentPage = this.searchListQuery.currentPage
        this.searchListQuery = { ... this.defaultQuery }
        this.searchListQuery.size = size
        this.searchListQuery.currentPage = currentPage
        this.searchListQuery[this.textCol] = this.textValue
        this.searchListQuery.oneCategoryId = this.categoryIds.length > 0 ? this.categoryIds[0] : ''
        this.searchListQuery.twoCategoryId = this.categoryIds.length > 1 ? this.categoryIds[1] : ''
        this.searchListQuery.threeCategoryId = this.categoryIds.length > 2 ? this.categoryIds[2] : ''
        if (this.purchaseOrderObj.supplierId) {
          this.searchListQuery.supplierId = this.purchaseOrderObj.supplierId
        }
        this.searchListQuery.purchaseOrderId = this.purchaseOrderObj.purchaseOrderId
        pagingPurchaseOrderGoods(this.searchListQuery).then(response => {
          this.listLoading = false
          this.total = response.data.total
          this.dataList = response.data.records
        })
      },
      // 采购单审核打开事件
      doAuditOrder() {
        this.auditForm = {
          purchaseOrderId: this.purchaseOrderObj.purchaseOrderId,
          purchaseOrderStatus: 2,
          auditRemark: ''
        }
        this.auditVisible = true
      },
      // 采购单审核确定事件
      doSaveAudit() {
        if (this.purchaseOrderObj.zeroPriceFlag === 1 && this.auditForm.purchaseOrderStatus === 2) {
          this.$confirm('采购单中含有单价为0的商品，是否继续审核？', '提示', {
            confirmButtonText: '继续审核',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.saveAudit()
          }).catch(() => {
          })
        } else {
          this.saveAudit()
        }
      },
      // 审核处理
      saveAudit() {
        this.fullLoading = true
        doAudit(this.auditForm).then(response => {
          if (response.isError) {
            this.fullLoading = false
            return
          }
          this.auditVisible = false
          this.$message({ type: 'success', message: '审核成功' })
          this.init()
        })
      },
      // 重算价格事件
      doRestSupplierPrice(purchaseOrderGoodsId) {
        var form = {}
        if (purchaseOrderGoodsId) {
          form.purchaseOrderGoodsId = purchaseOrderGoodsId
        } else {
          form.purchaseOrderId = this.purchaseOrderObj.purchaseOrderId
          this.listLoading = true
        }
        doRestPrice(form).then(response => {
          if (response.isError) {
            this.listLoading = false
            return
          }
          this.$message({ type: 'success', message: '保存成功' })
          if (purchaseOrderGoodsId) {
            const data = response.data
            this.$refs['orderGoodsForm'].resetFields()
            this.orderGoodsForm.warehouseGoodsPrice = data.warehouseGoodsPrice
            this.orderGoodsForm.taxFlag = data.taxFlag.toString()
          }
          this.init()
          this.initList()
        })
      },
      // 终止事件
      doStopOrder() {
        var totalWaitWarehouseOutNum = 0
        var notWarehouseOutNum = 0
        this.dataList.forEach(item => {
          totalWaitWarehouseOutNum += item.waitWarehouseOutNum
          notWarehouseOutNum += item.notWarehouseOutNum
        })
        if (totalWaitWarehouseOutNum > 0) {
          this.$message({
            type: 'error',
            message: '采购退货申请存在未确认的出库数量，不允许终止!'
          })
          return
        }
        var tips = '确定要终止采购单吗?'
        if (notWarehouseOutNum > 0) {
          tips = '采购退货申请还有' + notWarehouseOutNum + '件商品未出库，终止后将不能再继续出库，确定要终止当前采购退货申请？'
        }
        this.$confirm(tips, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          var purchaseOrderIds = []
          purchaseOrderIds.push(this.purchaseOrderObj.purchaseOrderId)
          updateBatchPurchaseOrderStatusByIds(purchaseOrderIds, -2, '手动终止').then(response => {
            if (response.isError) return
            this.$message({
              type: 'success',
              message: '终止成功'
            })
          })
        }).catch(() => {})
      },
      // 返回事件
      doBack() {
        this.$router.go(-1)
      },
      // 粘贴板复制事件
      doClipboard(text, event) {
        clipboard(text, event)
      },
      // 查询事件
      doSearch() {
        this.searchListQuery.currentPage = 1
        this.initList()
      },
      // 重置事件
      doResetSearch() {
        const originData = this.$options.data()
        this.textCol = originData.textCol
        this.textValue = originData.textValue
        this.categoryIds = originData.categoryIds
        this.defaultQuery = originData.defaultQuery
        this.doSearch()
      },
      // 编辑事件
      doEdit(row) {
        const originData = this.$options.data()
        this.orderGoodsForm = originData.orderGoodsForm
        Object.assign(this.orderGoodsForm, row)
        if (this.$refs['orderGoodsForm']) this.$refs['orderGoodsForm'].resetFields()
        this.orderGoodsForm.taxFlag = this.orderGoodsForm.taxFlag.toString()
        this.orderGoodsVisible = true
      },
      // 订单商品数量价格保存事件
      doSaveOrderGoods() {
        this.$refs['orderGoodsForm'].validate((valid) => {
          if (valid) {
            if (parseFloat(this.orderGoodsForm.warehouseGoodsPrice) === 0) {
              this.$confirm('商品单价为0，是否确认继续保存？', '提示', {
                confirmButtonText: '继续保存',
                cancelButtonText: '取消',
                type: 'warning'
              }).then(() => {
                this.saveOrderGoods()
              }).catch(() => {
              })
            } else {
              this.saveOrderGoods()
            }
          }
        })
      },
      // 编辑商品保存
      saveOrderGoods() {
        savePurchaseOrderGoods(this.orderGoodsForm).then(response => {
          if (response.isError) return
          this.$message({ type: 'success', message: '保存成功' })
          this.orderGoodsVisible = false
          this.init()
          this.initList()
        })
      },
      // 更改当前页数
      handleCurrentChange(val) {
        this.searchListQuery.currentPage = val
        this.initList()
      },
      // 更改当前页面大小
      handleSizeChange(val) {
        this.searchListQuery.size = val
        this.initList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .text-input {
    width: 200px !important;
  }
  .supplier-select {
    /deep/ .el-input {
      width: 180px !important;
    }
  }
  .user-avatar {
    width: 80px;
    height: 80px;
    display: block;
    padding: 1px;
    border: #efefef 1px solid;
  }
</style>
